import { readFile } from 'fs/promises';
import { Plugin } from 'vite';
import path from 'path';

/**
 * Vite插件，用于预处理@iconify/json的图标集数据
 */
export function iconCollectionsPlugin(): Plugin {
    return {
        name: 'icon-collections',
        async resolveId(id) {
            if (id === '@iconify-collections') {
                return id;
            }
            return null;
        },
        async load(id) {
            if (id === '@iconify-collections') {
                try {
                    // 读取@iconify/json中的collections.json文件
                    const collectionsPath = path.resolve(
                        __dirname, '../../node_modules/@iconify/json/collections.json'
                    );
                    const content = await readFile(collectionsPath, 'utf-8');
                    const collectionsObj = JSON.parse(content);

                    // 将对象转换为数组，并为每个元素添加icons属性
                    const collections = Object.entries(collectionsObj).map(([key, value]) => ({
                        id: key,  // 保留原始键作为id
                        ...value,  // 展开原始属性
                        icons: []  // 添加空的icons数组
                    }));
                    collections.forEach(async(collection) => {
                        const iconPath = path.resolve(
                            __dirname, '../../node_modules/@iconify/json/json/' + collection.id + '.json'
                        );
                        const content = await readFile(collectionsPath, 'utf-8');
                        const iconsObj = JSON.parse(content);
                        collection.icons = iconsObj.icons;
                    })

                    // 返回处理后的数据
                    return `export const collections = ${JSON.stringify(collections)};`;
                } catch (error) {
                    console.error('Failed to load icon collections:', error);
                    // 返回默认数据作为后备
                    return `export const collections = [];`;
                }
            }
            return null;
        },
    };
}